'use client';

import { useState, useEffect } from 'react';
import GlassCard from '@/components/ui/GlassCard';
import { FileText, Database, Users, TrendingUp, Loader2 } from 'lucide-react';
import toast from 'react-hot-toast';
import { useAuthStore } from '@/store/authStore';

interface DashboardStats {
  documents: { total: number; growth: string };
  knowledge_bases: { total: number; growth: string };
  users: { total: number; growth: string };
  weekly_queries: { total: number; growth: string };
  recent_documents: Array<{
    id: string;
    title: string;
    file_name: string;
    upload_time: string;
    file_type: string;
  }>;
}

export default function DashboardPage() {
  const [stats, setStats] = useState<DashboardStats | null>(null);
  const [loading, setLoading] = useState(true);
  const { user } = useAuthStore();

  useEffect(() => {
    loadStats();
  }, []);

  const loadStats = async () => {
    try {
      const { statsApi } = await import('@/lib/api');
      const data = await statsApi.getDashboard();
      setStats(data);
    } catch (error: any) {
      toast.error('加载统计数据失败');
      console.error('加载统计数据失败:', error);
    } finally {
      setLoading(false);
    }
  };

  if (loading) {
    return (
      <div className="flex items-center justify-center h-64">
        <Loader2 className="h-8 w-8 text-blue-500 animate-spin" />
      </div>
    );
  }

  const statsCards = [
    {
      icon: FileText,
      label: '文档总数',
      value: stats?.documents.total.toLocaleString() || '0',
      trend: stats?.documents.growth || '0%',
      color: 'text-blue-500 dark:text-blue-400',
      bgGradient: 'from-blue-500/10 to-cyan-500/10',
    },
    {
      icon: Database,
      label: '知识库',
      value: stats?.knowledge_bases.total.toString() || '0',
      trend: stats?.knowledge_bases.growth || '0',
      color: 'text-purple-500 dark:text-purple-400',
      bgGradient: 'from-purple-500/10 to-pink-500/10',
    },
    {
      icon: Users,
      label: '用户数',
      value: stats?.users.total.toLocaleString() || '0',
      trend: stats?.users.growth || '0%',
      color: 'text-emerald-500 dark:text-emerald-400',
      bgGradient: 'from-emerald-500/10 to-teal-500/10',
    },
    {
      icon: TrendingUp,
      label: '本周查询',
      value: stats?.weekly_queries.total.toLocaleString() || '0',
      trend: stats?.weekly_queries.growth || '0%',
      color: 'text-rose-500 dark:text-rose-400',
      bgGradient: 'from-rose-500/10 to-pink-500/10',
    },
  ];

  return (
    <div className="space-y-6">
      {/* Welcome banner */}
      <GlassCard className="p-8 bg-gradient-to-br from-indigo-50/50 via-purple-50/50 to-pink-50/50 dark:from-transparent dark:via-transparent dark:to-transparent border border-indigo-100 dark:border-white/20">
        <h2 className="text-3xl font-bold mb-2">
          <span className="bg-gradient-to-r from-indigo-600 via-purple-600 to-pink-600 bg-clip-text text-transparent dark:from-indigo-300 dark:via-purple-300 dark:to-pink-300">
            欢迎回来，{user?.username || 'Admin'}！
          </span>
        </h2>
        <p className="text-gray-600 dark:text-white/70 text-lg">
          今天是 {new Date().toLocaleDateString('zh-CN', { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' })}
        </p>
      </GlassCard>

      {/* Stats grid */}
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
        {statsCards.map((stat) => {
          const Icon = stat.icon;
          return (
            <GlassCard 
              key={stat.label} 
              variant="hover" 
              className={`p-6 bg-gradient-to-br ${stat.bgGradient} border border-gray-200/60 dark:border-white/20 hover:border-gray-300/80 dark:hover:border-white/30 transition-all`}
            >
              <div className="flex items-center justify-between mb-4">
                <div className={`p-3 rounded-2xl bg-gradient-to-br ${stat.bgGradient}`}>
                  <Icon className={`h-6 w-6 ${stat.color}`} />
                </div>
                <span className={`text-sm font-semibold px-2.5 py-1 rounded-full ${
                  stat.trend.startsWith('+') ? 'text-emerald-600 bg-emerald-50 dark:text-emerald-400 dark:bg-emerald-500/10' : 
                  stat.trend.startsWith('-') ? 'text-red-600 bg-red-50 dark:text-red-400 dark:bg-red-500/10' : 
                  'text-gray-600 bg-gray-50 dark:text-gray-400 dark:bg-gray-500/10'
                }`}>
                  {stat.trend}
                </span>
              </div>
              <h3 className="text-3xl font-bold bg-gradient-to-r from-gray-900 to-gray-700 bg-clip-text text-transparent dark:from-white dark:to-gray-200 mb-2">
                {stat.value}
              </h3>
              <p className="text-gray-500 dark:text-white/60 text-sm font-medium">{stat.label}</p>
            </GlassCard>
          );
        })}
      </div>

      {/* Recent activity */}
      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
        <GlassCard className="p-6 border border-gray-200/60 dark:border-white/20">
          <h3 className="text-xl font-bold bg-gradient-to-r from-gray-900 to-gray-700 bg-clip-text text-transparent dark:from-white dark:to-gray-200 mb-4 flex items-center gap-2">
            <FileText className="h-5 w-5 text-blue-500" />
            最近上传
          </h3>
          <div className="space-y-2">
            {stats?.recent_documents && stats.recent_documents.length > 0 ? (
              stats.recent_documents.map((doc) => (
                <div
                  key={doc.id}
                  className="flex items-center gap-3 p-3 rounded-xl bg-gradient-to-r from-gray-50/80 to-blue-50/50 dark:from-white/5 dark:to-blue-500/5 hover:from-gray-100 hover:to-blue-100/80 dark:hover:from-white/10 dark:hover:to-blue-500/10 transition-all duration-300 border border-gray-200/40 dark:border-white/10 hover:border-blue-200/60 dark:hover:border-blue-400/20"
                >
                  <div className="p-2 rounded-lg bg-blue-100 dark:bg-blue-500/20">
                    <FileText className="h-4 w-4 text-blue-600 dark:text-blue-400" />
                  </div>
                  <div className="flex-1 min-w-0">
                    <p className="text-gray-800 dark:text-white/90 text-sm font-medium truncate">
                      {doc.title}
                    </p>
                    <p className="text-gray-500 dark:text-white/60 text-xs">{doc.upload_time}</p>
                  </div>
                </div>
              ))
            ) : (
              <p className="text-gray-500 dark:text-white/60 text-sm text-center py-4">
                暂无最近上传的文档
              </p>
            )}
          </div>
        </GlassCard>

        <GlassCard className="p-6">
          <h3 className="text-xl font-bold text-gray-900 dark:text-white mb-4">快速操作</h3>
          <div className="grid grid-cols-2 gap-3">
            <a
              href="/dashboard/documents"
              className="glass p-4 rounded-lg hover:bg-gray-200/50 dark:hover:bg-white/20 transition-all hover:scale-105 cursor-pointer block text-center"
            >
              <FileText className="h-6 w-6 text-gray-700 dark:text-white/80 mx-auto mb-2" />
              <span className="text-gray-800 dark:text-white/90 text-sm">上传文档</span>
            </a>
            <a
              href="/dashboard/knowledge-base"
              className="glass p-4 rounded-lg hover:bg-gray-200/50 dark:hover:bg-white/20 transition-all hover:scale-105 cursor-pointer block text-center"
            >
              <Database className="h-6 w-6 text-gray-700 dark:text-white/80 mx-auto mb-2" />
              <span className="text-gray-800 dark:text-white/90 text-sm">新建知识库</span>
            </a>
          </div>
        </GlassCard>
      </div>
    </div>
  );
}
